import {
    EntityComponentTypes,
    ItemLockMode,
    ItemStack,
} from "@minecraft/server";
import { Dimensions } from "@sapi-game/constants";
import { Game, GameComponent } from "@sapi-game/main";
import { Duration } from "@sapi-game/utils";
import { CvSMainState } from "../mainState";

export class CvSIronManager extends GameComponent<CvSMainState> {
    private readonly iron_bars = new ItemStack("iron_bars");

    override onAttach(): void {
        this.iron_bars.setCanPlaceOn(["iron_bars"]);
        this.iron_bars.lockMode = ItemLockMode.inventory;
        //刷新
        this.subscribe(
            Game.events.interval,
            () => this.refresh(),
            Duration.fromSeconds(this.context.config.ironRefreshInterval)
        );
        //检测背包
        this.subscribe(
            Game.events.interval,
            () => {
                this.context.shepherd.forEach((p) => {
                    const container = p.player.getComponent(
                        EntityComponentTypes.Inventory
                    )?.container;
                    if (!container) return;
                    let ironCnt = 0;
                    //遍历容器
                    for (let i = 0; i < container.size; i++) {
                        const item = container.getItem(i);
                        if (item?.typeId == "minecraft:iron_ingot") {
                            ironCnt += item.amount;
                        }
                    }
                    //给铁栏杆，清铁锭
                    if (ironCnt >= 10) {
                        p.runCommand("clear @s iron_ingot 0 10");
                        p.sendMessage("10个铁锭已自动兑换为铁栏杆");
                        p.giveItem(this.iron_bars);
                    }
                });
            },
            new Duration(20)
        );
    }

    refresh() {
        const iron = new ItemStack("iron_ingot");
        for (const point of this.context.map.ironPoints) {
            try {
                const block = Dimensions.Overworld.getBlock(point);
                if (!block) continue;
                Dimensions.Overworld.spawnItem(iron, block.center());
            } catch (err) {}
        }
    }
}
